package com.yjc.drygoods.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yjc.common.constant.ExchangeDetailStatusEnum;
import com.yjc.common.constant.PurchaseDetailStatusEnum;
import com.yjc.common.utils.R;
import com.yjc.drygoods.ware.entity.ExchangeDetailEntity;
import com.yjc.drygoods.ware.entity.PurchaseDetailEntity;
import com.yjc.drygoods.ware.feign.ProductFeignService;
import com.yjc.drygoods.ware.to.SpuInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.Query;

import com.yjc.drygoods.ware.dao.BatchesDao;
import com.yjc.drygoods.ware.entity.BatchesEntity;
import com.yjc.drygoods.ware.service.BatchesService;
import org.springframework.util.StringUtils;

@Slf4j
@Service("batchesService")
public class BatchesServiceImpl extends ServiceImpl<BatchesDao, BatchesEntity> implements BatchesService {

    @Autowired
    ProductFeignService productFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BatchesEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.like("spu_name", key);
        }
        IPage<BatchesEntity> page = this.page(
                new Query<BatchesEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据商品id查询商品批次
     *
     * @param spuId
     * @return
     */
    @Override
    public BatchesEntity getSpuBatch(Long spuId) {
        return this.getOne(new QueryWrapper<BatchesEntity>().eq("spu_id", spuId));
    }

    /**
     * 批量保存或更新商品批次
     *
     * @param purchaseDetailEntities
     */
    @Override
    public void saveOrUpdateBatches(List<PurchaseDetailEntity> purchaseDetailEntities) {
        List<Long> resList = purchaseDetailEntities
                .stream()
                .filter(item -> item.getStatus() == PurchaseDetailStatusEnum.FINISHED.getCode())
                .map(PurchaseDetailEntity::getSpuId)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, PurchaseDetailEntity> purMap = purchaseDetailEntities
                .stream()
                .filter(item -> item.getStatus() == PurchaseDetailStatusEnum.FINISHED.getCode())
                .collect(Collectors.toMap(PurchaseDetailEntity::getSpuId, item -> item));
        //resList已去重
        List<BatchesEntity> batchesEntities = this.baseMapper.selectList(new QueryWrapper<BatchesEntity>().in("spu_id", resList));

        if (batchesEntities != null && batchesEntities.size() > 0) {
            List<BatchesEntity> collect = batchesEntities.stream().map(batchesEntity -> {
                //将已存在批次信息的spuId去掉，剩下的都是不存在批次信息的spuId
                resList.remove(batchesEntity.getSpuId());
                batchesEntity.setBatch(batchesEntity.getBatch() + 1);
                PurchaseDetailEntity purchaseDetailEntity = purMap.get(batchesEntity.getSpuId());
                batchesEntity.setSupplierId(purchaseDetailEntity.getSupplierId());
                batchesEntity.setSupplierName(purchaseDetailEntity.getSupplierName());
                batchesEntity.setSpuNum(purchaseDetailEntity.getSpuNum());
                batchesEntity.setSpuPrice(purchaseDetailEntity.getSingleSpuPrice());
                batchesEntity.setUpdateTime(new Date());
                return batchesEntity;
            }).collect(Collectors.toList());
            //更新干货批次信息
            this.updateBatchById(collect);
        }

        List<BatchesEntity> collect = resList.stream().map(item -> {
            BatchesEntity batchesEntity = new BatchesEntity();
            R r = productFeignService.spuInfo(item);
            if (r.getCode() != 0) {
                throw new RuntimeException("干货远程服务调用异常");
            }
            SpuInfoTo spuInfo = r.getData("spuInfo", new TypeReference<SpuInfoTo>() {
            });
            batchesEntity.setSpuName(spuInfo.getSpuName());
            batchesEntity.setUpdateTime(new Date());
            batchesEntity.setBatch(1);
            batchesEntity.setSpuId(item);
            PurchaseDetailEntity purchaseDetailEntity = purMap.get(item);
            batchesEntity.setSupplierId(purchaseDetailEntity.getSupplierId());
            batchesEntity.setSupplierName(purchaseDetailEntity.getSupplierName());
            batchesEntity.setSpuPrice(purchaseDetailEntity.getSingleSpuPrice());
            batchesEntity.setSpuNum(purchaseDetailEntity.getSpuNum());
            return batchesEntity;
        }).collect(Collectors.toList());
        //保存干货批次信息
        this.saveBatch(collect);

    }

    @Override
    public void saveOrUpdateBatchesToEx(List<ExchangeDetailEntity> exchangeDetailEntities) {
        List<Long> resList = exchangeDetailEntities
                .stream()
                .filter(item -> item.getStatus() == ExchangeDetailStatusEnum.FINISHED.getCode())
                .map(ExchangeDetailEntity::getAfterSpuId)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, ExchangeDetailEntity> exMap = exchangeDetailEntities
                .stream()
                .filter(item -> item.getStatus() == ExchangeDetailStatusEnum.FINISHED.getCode())
                .collect(Collectors.toMap(ExchangeDetailEntity::getAfterSpuId, item -> item));
        //resList已去重
        List<BatchesEntity> batchesEntities = this.baseMapper.selectList(new QueryWrapper<BatchesEntity>().in("spu_id", resList));

        if (batchesEntities != null && batchesEntities.size() > 0) {
            List<BatchesEntity> collect = batchesEntities.stream().map(batchesEntity -> {
                //将已存在批次信息的spuId去掉，剩下的都是不存在批次信息的spuId
                resList.remove(batchesEntity.getSpuId());
                batchesEntity.setBatch(batchesEntity.getBatch() + 1);
                ExchangeDetailEntity exchangeDetailEntity = exMap.get(batchesEntity.getSpuId());
                batchesEntity.setSupplierId(exchangeDetailEntity.getSupplierId());
                batchesEntity.setSupplierName(exchangeDetailEntity.getSupplierName());
                batchesEntity.setSpuNum(exchangeDetailEntity.getAfterSpuNum());
                batchesEntity.setSpuPrice(exchangeDetailEntity.getAfterSpuPrice());
                batchesEntity.setUpdateTime(new Date());
                return batchesEntity;
            }).collect(Collectors.toList());
            //更新干货批次信息
            this.updateBatchById(collect);
        }

        List<BatchesEntity> collect = resList.stream().map(item -> {
            BatchesEntity batchesEntity = new BatchesEntity();
            R r = productFeignService.spuInfo(item);
            if (r.getCode() != 0) {
                throw new RuntimeException("干货远程服务调用异常");
            }
            SpuInfoTo spuInfo = r.getData("spuInfo", new TypeReference<SpuInfoTo>() {
            });
            batchesEntity.setSpuName(spuInfo.getSpuName());
            batchesEntity.setUpdateTime(new Date());
            batchesEntity.setBatch(1);
            batchesEntity.setSpuId(item);
            ExchangeDetailEntity exchangeDetailEntity = exMap.get(item);
            batchesEntity.setSupplierId(exchangeDetailEntity.getSupplierId());
            batchesEntity.setSupplierName(exchangeDetailEntity.getSupplierName());
            batchesEntity.setSpuNum(exchangeDetailEntity.getAfterSpuNum());
            batchesEntity.setSpuPrice(exchangeDetailEntity.getAfterSpuPrice());
            return batchesEntity;
        }).collect(Collectors.toList());
        //保存干货批次信息
        this.saveBatch(collect);
    }

}